<template>
  <div class="custom-form">
    <el-row :gutter="15">
      <el-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="100px"
        :key="showFormKey" v-if="showForm">
        <el-col :span="8" v-show="hasFormPermission('order_number')">
          <el-form-item :label="$t('工单编号')" prop="order_number">
            <el-input v-model="formData['order_number']" placeholder="工单编号"
              :disabled="hasDisabledPermission('order_number',undefined)"
              :readonly="!hasEditPermission('order_number',true)" :style="{width: '100%'}"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('create_date')">
          <el-form-item :label="$t('日期')" prop="create_date">
            <el-date-picker :disabled="hasDisabledPermission('create_date',false)"
              :readonly="!hasEditPermission('create_date',false)" v-model="formData['create_date']"
              format="yyyy-MM-dd" value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择日期"
              clearable></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('order_id')">
          <el-form-item :label="$t('销售订单编号')" prop="order_id">
            <el-input v-model="formData['order_id_showValue']" placeholder="请选择销售订单编号"
              :disabled="hasDisabledPermission('order_id',false)"
              :readonly="!hasEditPermission('order_id',undefined)" clearable
              suffix-icon='el-icon-more' :style="{width: '100%'}"
              @focus='autoHandlerClick(autoHandlerClickConfig(102))'
              @clear="clearBombLayerFormData('order_id')"></el-input>
            <el-form-item prop="order_id" style="display:none">
              <el-input v-model="formData['order_id']"></el-input>
            </el-form-item>
          </el-form-item>
        </el-col>
        <avue-filterable-data-list type="single" :conf="autoCompleteConf" v-if="autoCompleteDialogVisible"
          v-on:onHandler="filterableCallBack"></avue-filterable-data-list>
        <el-col :span="8" v-show="hasFormPermission('service_provider_id')">
          <el-form-item :label="$t('服务商名称')" prop="service_provider_id">
            <el-input v-model="formData['service_provider_id']" placeholder="请输入服务商名称"
              :disabled="hasDisabledPermission('service_provider_id',false)"
              :readonly="!hasEditPermission('service_provider_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('customer_id')">
          <el-form-item :label="$t('客户名称')" prop="customer_id">
            <el-input v-model="formData['customer_id']" placeholder="请输入客户名称"
              :disabled="hasDisabledPermission('customer_id',false)"
              :readonly="!hasEditPermission('customer_id',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8" v-show="hasFormPermission('customer_phone')">
          <el-form-item :label="$t('客户联系方式')" prop="customer_phone">
            <el-input v-model="formData['customer_phone']" placeholder="请输入客户联系方式"
              :disabled="hasDisabledPermission('customer_phone',false)"
              :readonly="!hasEditPermission('customer_phone',false)" clearable :style="{width: '100%'}">
            </el-input>
          </el-form-item>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('table115824398679405060000')">
          <avue-form v-loading="preloadLoading106" class=" avueFormTitleNoWrap  subTableForm "
            element-loading-text="数据预加载中..." element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.7)" :option="option106"
            v-model="table115824398679405060000" ref="avueTabletable115824398679405060000"
            v-show="hasFormPermission('table115824398679405060000')" :disabled="disabled" v-if="reRenderSubform">
          </avue-form>
        </el-col>
        <!-- <el-col :span="24" v-show="hasFormPermission('description')">
          <el-form-item :label="$t('申请售后原因')" prop="description">
            <el-select v-model="formData['description']" placeholder="请选择申请售后原因"
              :disabled="hasDisabledPermission('description',false)" filterable clearable
              :style="{width: '100%'}">
              <el-option v-for="(item, index) in descriptionOptions" :key="index" :label="item.F_ItemName"
                :value="item.F_ItemValue" :disabled="item.disabled"></el-option>
            </el-select>
          </el-form-item>
        </el-col> -->
		<el-col :span="24" v-show="hasFormPermission('description')">
		  <el-form-item :label="$t('申请售后原因')" prop="description">
		    <el-input v-model="service_support_order_table2['description']" placeholder="请输入申请售后原因"
		      :disabled="hasDisabledPermission('description',false)"
		      :readonly="!hasEditPermission('description',false)" clearable :style="{width: '100%'}">
		    </el-input>
		  </el-form-item>
		</el-col>
        <el-col :span="24" v-show="hasFormPermission('service_support_order_table_detailsEntityList')">
          <avue-form v-loading="preloadLoading116" class=" avueFormTitleNoWrap  subTableForm "
            element-loading-text="数据预加载中..." element-loading-spinner="el-icon-loading"
            element-loading-background="rgba(0, 0, 0, 0.7)" :option="option116"
            v-model="service_support_order_table_detailsEntityList" ref="avueTableservice_support_order_table_detailsEntityList"
            v-show="hasFormPermission('service_support_order_table_detailsEntityList')" :disabled="disabled" v-if="reRenderSubform">
          </avue-form>
        </el-col>
        <el-col :span="24" v-show="hasFormPermission('expected_date')">
          <el-form-item :label="$t('希望上门时间')" prop="expected_date">
            <el-date-picker :disabled="hasDisabledPermission('expected_date',false)"
              :readonly="!hasEditPermission('expected_date',false)" type="datetime"
              v-model="service_support_order_table2['expected_date']" format="yyyy-MM-dd"
              value-format="yyyy-MM-dd" :style="{width: '100%'}" placeholder="请选择希望上门时间" clearable>
            </el-date-picker>
          </el-form-item>
        </el-col> 
        <el-col :span="24" >
          <el-form-item size="large" v-if="isEdit" class="form-button-center">
            <el-button type="primary" @click="submitForm" :loading="submitLoading">
              {{submitLoading?$t('workFlow.WFMenu.hintSubmit'):$t('submit')}}</el-button>
            <el-button @click="cancelForm">{{$t('cancelText')}}</el-button>
          </el-form-item>
        </el-col>
      </el-form>
    </el-row>
  </div>
</template>
<script>

        import authorizeMixin from "@/mixins/authorize";
        import { baseUrl } from "@/config/env";
        import request from "@/router/axios";
         import {fieldsConfig,formFieldsMap,getHideComponents} from './Work_orderConfig'
		import { formValidateNotice } from '@/util/util';
        export default {
          mixins: [authorizeMixin],
       
  components: {},
  props: ['keyValue', 'isEdit', 'disabled'],
  data() {
    return {
      userInfo: {},
      submitLoading: false,
      showForm: true,
      showFormKey: 1,
      reRenderSubform: false,
      operationVal: 'add',
      isAdd: true,
	  order_number:'',
      addressUrl:'service_support_order_service',
      autoCompleteConfEventData: [],
      mainTableName: 'service_support_order',
      formConfig: {},
      formFieldsMap: new Map(),
      hideComponentsMap: new Map(),
      needShowValueTags: ['asso-popup', 'mutiple-popup'],
      autoCompleteConf: {},
      autoCompleteDialogVisible: false,
      formData: {
        'order_number': '',
        'create_date': null,
        'order_id_showValue': '',
        'order_id': '',
        'service_provider_id': '',
        'customer_id': '',
        'customer_phone': '',
      },
      rules: {
        order_number: [],
        create_date: [{
          required: true,
          message: '请选择日期',
          trigger: 'change'
        }],
        order_id: [{
          required: true,
          message: '请选择销售订单编号',
          trigger: 'change'
        }],
        service_provider_id: [{
          required: true,
          message: '请输入服务商名称',
          trigger: 'blur'
        }],
        customer_id: [{
          required: true,
          message: '请输入客户名称',
          trigger: 'blur'
        }],
        customer_phone: [{
          required: true,
          message: '请输入客户联系方式',
          trigger: 'blur'
        }],
        description: [],
        expected_date: [],
      },
      order_idOptions: [],
      table115824398679405060000: {},
      preloadLoading106: false,
      order_table_idOptions: [],
	  service_support_order_table2:{
		  'description': '',
		  'expected_date': null,
	  },
      service_support_order_table_detailsEntityList: {},
      preloadLoading116: false,
    }
  },
  computed: {
    option106() {
      return {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        disabled: this.disabled,
        column: [{
          label: '订单明细',
          prop: 'table115824398679405060000',
          type: 'dynamic',
          span: 24,
          children: {
            align: 'center',
            headerAlign: 'center',
            rowAdd: (done) => {
              // this.$message.success('新增回调');
              done({});
            },
            rowDel: (row, done) => {
              this.reRenderSubform = false; //更新组件 index
              setTimeout(() => {
                // this.$message.success('删除回调'+JSON.stringify(row));
                this.reRenderSubform = true;
              }, 0);
              done();
            },
            column: this.getAuthorityTableChildrenList('table115824398679405060000', [{
              label: this.$t('组件名称'),
              prop: 'assembly_name',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入组件名称',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '组件名称不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '组件名称不能为空'
              }, ],
            }, {
              label: this.$t('订单时间'),
              prop: 'order_data',
              value: '',
              type: 'datetime',
              width: null,
              placeholder: '请选择订单时间',
              'value-format': 'yyyy-MM-dd',
              format: 'yyyy-MM-dd',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '订单时间不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '订单时间不能为空'
              }, ],
            }, {
              label: this.$t('合同号'),
              prop: 'contract_number',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入合同号',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '合同号不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '合同号不能为空'
              }, ],
            }, {
              label: this.$t('合同开始时间'),
              prop: 'contract_start_date',
              value: '',
              type: 'datetime',
              width: null,
              placeholder: '请选择合同开始时间',
              'value-format': 'yyyy-MM-dd',
              format: 'yyyy-MM-dd',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '合同开始时间不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '合同开始时间不能为空'
              }, ],
            }, {
              label: this.$t('合同结束时间'),
              prop: 'contract_end_date',
              value: '',
              type: 'datetime',
              width: null,
              placeholder: '请选择合同结束时间',
              'value-format': 'yyyy-MM-dd',
              format: 'yyyy-MM-dd',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '合同结束时间不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '合同结束时间不能为空'
              }, ],
            }, ])
          }
        }, ],
      }
    },
    option116() {
      return {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: 100,
        disabled: this.disabled,
        column: [{
          label: '问题描述',
          prop: 'service_support_order_table_detailsEntityList',
          type: 'dynamic',
          span: 24,
          children: {
            align: 'center',
            headerAlign: 'center',
            rowAdd: (done) => {
              // this.$message.success('新增回调');
              done({});
            },
            rowDel: (row, done) => {
              this.reRenderSubform = false; //更新组件 index
              setTimeout(() => {
                // this.$message.success('删除回调'+JSON.stringify(row));
                this.reRenderSubform = true;
              }, 0);
              done();
            },
            column: this.getAuthorityTableChildrenList('service_support_order_table_detailsEntityList', [{
              label: this.$t('问题详细描述'),
              prop: 'description',
              value: '',
              type: 'textarea',
              width: null,
              placeholder: '请输入问题详细描述',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '问题详细描述不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '问题详细描述不能为空'
              }, ],
            }, {
              label: this.$t('问题截图'),
              prop: 'upload',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入问题截图',
              required: false,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [],
              ruleList: [],
            }, 
			{
			  label: this.$t('对接人姓名'),
			  prop: 'contactor',
			  value: '',
			  type: 'input-tip',
			  width: null,
			  placeholder: '请输入对接人姓名',
			  required: true,
			  formslot: false,
			  disabled: this.disabled ? this.disabled : false,
			  rules: [{
			    required: true,
			    message: '对接人姓名不能为空'
			  }, ],
			  ruleList: [{
			    required: true,
			    message: '对接人姓名不能为空'
			  }, ],
			}, 
			{
              label: this.$t('对接人联系电话'),
              prop: 'phone',
              value: '',
              type: 'input-tip',
              width: null,
              placeholder: '请输入对接人联系电话',
              required: true,
              formslot: false,
              disabled: this.disabled ? this.disabled : false,
              rules: [{
                required: true,
                message: '对接人联系电话不能为空'
              }, ],
              ruleList: [{
                required: true,
                message: '对接人联系电话不能为空'
              }, ],
            }, ])
          }
        }, ],
      }
    },
  },
  watch: {},
  async created() {
    this.formConfig = this.getFormConfig();
    this.formFieldsMap = this.getFormFieldsMap();
    this.userInfo = localStorage.getItem("avue-userInfo") ? JSON.parse(localStorage.getItem(
      "avue-userInfo")).content : {};
	  console.log(this.keyValue)
  },
  async mounted() {
    this.hideComponentsMap = await this.getHideComponentsMap();
    this.showForm = false;
    await this.insertCreatedEvent();
    //TODO   再这里做数据回填 请求表单数据
   
           if(this.keyValue){
              this.isAdd = false;
          }
           if(!this.isAdd&&this.keyValue){
              this.operationVal = 'edit';
              try {
                let res = await request({
                  url: baseUrl + "/"+this.addressUrl+"/"+this.keyValue,
                  method: "get",
                });
                  
            this.formData = res.data.data.service_support_order
            
          this.table115824398679405060000.table115824398679405060000 = res.data.data.table115824398679405060000
          
          this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList = res.data.data.service_support_order_table_detailsEntityList
          
				if(this.formData.order_id){
					this.$set(this.formData,'order_id_showValue',this.formData.order_id)
          let config=this.autoHandlerClickConfig(102);
				  this.getMutipleAllData(this.formData,config,'order_id',102);
				}
				
        this.table115824398679405060000.table115824398679405060000.forEach(element => {
      });
      
        this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList.forEach(element => {
      });
      
                  await this.handleEdit();
                 this.showFormKey++;
              } catch (error) {
              }
          }

       
    if (typeof this.getField100Options == "function" && this.operationVal == 'add') {
      await this.getField100Options();
    }
    if (typeof this.getField102Options == "function") {
      await this.getField102Options();
    }
    // if (this.isAdd) {
    //   await this.preloadData106()
    // }
    if (typeof this.getField115Options == "function") {
      await this.getField115Options();
    }
    await this.insertMountedEvent();
    this.reRenderSubform = true; //子表单显示
    this.showFormKey++;
    this.processParameterAssignment();
    this.showForm = true;
  },
  methods: {
    getFormData() {
      let key = this.mainTableName + 'Entity';
      let returnParams = {};
      returnParams[key] = this.formData;
      return {
        ...returnParams,
		service_support_order_tableEntityList:[{...this.service_support_order_table2,...this.service_support_order_table_detailsEntityList}],
		service_support_serviceEntityList:[],
		
      };	  
    },
    validateForm() {
      this.$refs['elForm'].validate(valid => {});
    },
    async aysncValidateForm() {
      let validataArry = []
      let formValidateNotice = function formValidateNotice(obj, that, formAuth) {
        for (var o in obj) {
          if (!formAuth[o] && obj[o][0]) {
            that.$message({
              message: obj[o][0].message + ',' + that.$t('noFormAuth'),
              type: 'warning'
            });
            return;
          }
        }
      }
      if (this.table115824398679405060000.table115824398679405060000 && this.table115824398679405060000
        .table115824398679405060000.length > 0) {
        validataArry.push(new Promise((resolve, reject) => {
          this.$refs['avueTabletable115824398679405060000'].validate(valid => {
            resolve(valid)
          });
        }));
      }
      if (this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList && this.service_support_order_table_detailsEntityList
        .service_support_order_table_detailsEntityList.length > 0) {
        validataArry.push(new Promise((resolve, reject) => {
          this.$refs['avueTableservice_support_order_table_detailsEntityList'].validate(valid => {
            resolve(valid)
          });
        }));
      }
      validataArry.push(new Promise((resolve, reject) => {
        this.$refs['elForm'].validate((valid, object) => {
          if (!this.isWorkflowForm) formValidateNotice(object, this, this.formEnCodeList)
          resolve(valid)
        })
      }))
      let res = await Promise.all(validataArry)
      if (res.includes(false)) {
        return false
      }
      else {
        return true;
      }
    },
    changeTableData() {
      if (this.table115824398679405060000.table115824398679405060000 && this.table115824398679405060000
        .table115824398679405060000.length > 0) {
        this.table115824398679405060000.table115824398679405060000.forEach((element, index) => {
          let itemChild = {
            ...element
          }
          for (let [key, value] of Object.entries(itemChild)) {
            if (Array.isArray(value)) {
              itemChild[key] = value.join(',')
            }
          }
          this.table115824398679405060000.table115824398679405060000[index] = itemChild;
        });
      }
      else {
        this.table115824398679405060000.table115824398679405060000 = [];
      }
      if (this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList && this.service_support_order_table_detailsEntityList
        .service_support_order_table_detailsEntityList.length > 0) {
        this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList.forEach((element, index) => {
          let itemChild = {
            ...element
          }
          for (let [key, value] of Object.entries(itemChild)) {
            if (Array.isArray(value)) {
              itemChild[key] = value.join(',')
            }
          }
          this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList[index] = itemChild;
        });
      }
      else {
        this.service_support_order_table_detailsEntityList.service_support_order_table_detailsEntityList = [];
      }
    },
    async submitForm() {
      this.submitLoading = true;
      let valid = await this.aysncValidateForm();
      if (valid == false) {
        this.submitLoading = false;
        return false;
      }
      this.changeTableData();
      //格式化数据
      let newObj = this.getFormData();
      
        //如果没有传入参数就是新增
        if (!this.keyValue) {

          request({
            url: baseUrl + "/"+this.addressUrl,
            method: "post",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "新增成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
        else{

         request({
            url: baseUrl + "/"+this.addressUrl+"/" + this.keyValue,
            method: "put",
            data : newObj
          }).then((res) => {
            this.submitLoading = false;
            this.$notify({
              title: "成功",
              message: "修改成功",
              type: "success",
            });
             this.$emit("onChange",true)
          });

        }
       
       
      
      
      await this.handleSubmit();
    },
    cancelForm() {
      this.$emit("onChange", true)
    },
    formatTree(data, valueField, lableField, childField, type) {
      let tree = [];
      data.forEach((node, index) => {
        let newNode = {
          value: node[valueField],
          label: node[lableField],
        };
        if (type) {
          newNode.disabled = node[valueField] == undefined ? true : false
        }
        tree.push(newNode);
        if (node[childField] != null && node[childField].length > 0) {
          newNode.children = (this.formatTree(node[childField], valueField, lableField, childField,
          type));
        }
      }, this);
      return tree;
    },
    
          //辅助编辑 预留方法
          async handleEdit() {
            await this.insertEditEvent();
          },
          
    //FORM_EVENT_EDIT
    
        //辅助提交 预留方法
        async handleSubmit() {
          await this.insertSubmitEvent();
        },
        //辅助工作流提交 预留方法
        getHandleSubmitFormEvent() {
            
        },
        //辅助工作流表单事件 判断 表单事件是否已经执行过
        getisExecutedFormEvent() {
            let key = 'index'+this.$store.state.formParser.workflowFormTabIndexKey;
            return this.$store.state.formParser.isExecutedFormEvent[key]?this.$store.state.formParser.isExecutedFormEvent[key]:false;
            
        },
      
    async getField100Options() {
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url:  baseUrl + '/code-rules/ServiceSupportOrder/gen',
        });
        if (resp.data.data) {
          this.formData.order_number = resp.data.data;
        }
      }
      catch (error) {}
    },
    setModelValue(fields, autoBindFields, data) {
      fields.map(item => {
        if (item.__config__.componentName && item.__config__.componentName == 'avue-tabs') {
          let childrenObj = item.__config__.childrenObj || {};
          for (let key in childrenObj) {
            let children = childrenObj[key];
            this.setModelValue(children, autoBindFields, data);
          }
        }
        else {
          //找到对应formId 元素  key值为存储的对应formId
          if (Object.prototype.toString.call(autoBindFields) === '[object Array]') {
            autoBindFields.forEach(el => {
              if (el.component == item.__config__.formId) {
                this.formData[item.__vModel__] = data[el.bindField];
              }
            })
          }
          else {
            if (autoBindFields.hasOwnProperty(item.__config__.formId)) {
              //按绑定的自定义字段赋值
              this.formData[item.__vModel__] = data[autoBindFields[item.__config__.formId]];
            }
          }
        }
      });
      //更新表单校验
      // this.validateForm();
    },
    filterableCallBack(data) {
      if (!this.autoCompleteConf) {
        return false;
      }
      //弹窗关闭前回填数据  如果有选择数据项
      if (data) {
		  this.formData.service_provider_id = data.服务商;
		  this.order_number = data.销售合同编号;
		  this.preloadData106();
        let fields = this.getElements(this.formConfig.fields);
        let autoBindFields = this.autoCompleteConf.autoBindFields ? JSON.parse(this.autoCompleteConf
          .autoBindFields) : {};
        let saveField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemValue' : this.autoCompleteConf
          .saveField;
        let showField = this.autoCompleteConf.dataType == 'dataItem' ? 'F_ItemName' : this.autoCompleteConf
          .showField;
        this.setModelValue(this.formConfig.fields, autoBindFields, data);
        //自己赋值
        if (this.autoCompleteConf.dataType == 'dataItem') {
          for (let i = 0; i < fields.length; i++) {
            if (fields[i].__config__.formId == this.autoCompleteConf.formId) {
              this.formData[this.autoCompleteConf.model] = data[saveField];
              this.formData[this.autoCompleteConf.model + '_showValue'] = data[showField];
              break;
            }
          }
        }
        else {
          this.formData[this.autoCompleteConf.model] = data[saveField];
          this.formData[this.autoCompleteConf.model + '_showValue'] = data[showField];
        }
      }
      if (this.autoCompleteConfEventData && this.autoCompleteConfEventData.length > 0) {
        this.triggerEventHandler(this.autoCompleteConfEventData);
      }
      //关闭弹窗
      this.autoCompleteDialogVisible = false;
    },
    getElements(fields) {
      let _arr = [];
      fields.map(item => {
        if (item.__config__.componentName == 'avue-tabs') {
          let childrenObj = item.__config__.childrenObj || {};
          for (let key in childrenObj) {
            _arr.push(...this.getElements(childrenObj[key]));
          }
        }
        else {
          _arr.push(item);
        }
      });
      return (() => {
        return _arr;
      })();
    },
    autoHandlerClick(conf) {
      if (conf.eventData && conf.eventData.length > 0) {
        this.autoCompleteConfEventData = conf.eventData;
      }
      else {
        this.autoCompleteConfEventData = conf.eventData;
      }
      this.autoCompleteConf.title = conf.label + '-选择记录';
      this.autoCompleteConf.model = conf.model;
      this.autoCompleteConf.formId = conf.formId;
      this.autoCompleteConf.dataType = conf.dataType;
      switch (conf.dataType) {
        case 'dataSource':
          this.autoCompleteConf.dataSource = conf.dataSource;
          this.autoCompleteConf.tabName = 'base';
          break;
        case 'dataSql':
          this.autoCompleteConf.dataSource = conf.database;
          this.autoCompleteConf.tabName = 'sql';
          this.autoCompleteConf.sqlStr = conf.sql;
          break;
        case 'dataItem':
          this.autoCompleteConf.dataSource = conf.dataItem;
          this.autoCompleteConf.dataItem = conf.dataItem;
          this.autoCompleteConf.fields = ['F_ItemName', 'F_ItemValue'];
          break;
        case 'dataApi':
          this.autoCompleteConf.apiConfig = conf.apiConfig;
          this.autoCompleteConf.formFieldsMap = this.formFieldsMap;
          this.autoCompleteConf.formData = this.formData;
          this.autoCompleteConf.tabName = 'api';
          break;
          conf.showField = 'F_ItemName';
          conf.saveField = 'F_ItemValue';
          this.autoCompleteConf.tabName = 'item';
          break;
      }
      this.autoCompleteConf.showField = conf.showField;
      this.autoCompleteConf.saveField = conf.saveField;
      this.autoCompleteConf.autoBindFields = conf.autoBindFields;
      this.autoCompleteConf.defaultValue = this.formData[conf.model];
      this.autoCompleteDialogVisible = true;
    },
    //多选弹层 表单编辑时数据回显处理
    getMutipleAllData(formData, config, model, formId) {
      let datatype = config.dataType;
      let saveField = datatype == 'dataItem' ? 'F_ItemValue' : config.saveField
      let showField = datatype == 'dataItem' ? 'F_ItemName' : config.showField;
      if (datatype == 'dataSource' || datatype == 'dataSql') {
        if (config.dataSource) {
          this.changeMutipleData(formData,  baseUrl + '/data-sources/' + config.dataSource +
            '/data', model, saveField, showField)
        }
      }
      if (datatype == 'dataItem') {
        this.changeMutipleData(formData,  baseUrl + '/data-items/' + config.dataItem +
          '/detail', model, saveField, showField)
      }
      if (datatype == 'dataApi') {
        let config = this.autoHandlerClickConfig(formId);
        if (config.apiConfig) {
          this.changeMutipleDataFromApi(config.apiConfig, model);
        }
      }
    },
    autoHandlerClickConfig(formId) {
      return this.formFieldsMap.get(formId).__config__.autoHandlerConfig;
    },
    async changeMutipleDataFromApi(apiConfig, model) {
      let url =  baseUrl + '' + apiConfig.url;
      let res = await this.$axios({
        method: 'POST',
        url: url,
        headers: {},
        params: {},
        data: {},
      });
      if (res.data.data && apiConfig.dataSource && res.data.data[apiConfig.dataSource].length > 0 &&
        apiConfig.saveField) {
        let arr = this.formData[model].split(',');
        let arr1 = [];
        arr.forEach(it => {
          let temp = res.data.data[apiConfig.dataSource].find(o => {
            return o[apiConfig.saveField] == it
          });
          if (temp) {
            arr1.push(temp[apiConfig.showField])
          }
        })
        if (arr1.length > 0) {
          this.formData[model + '_showValue'] = arr1.join(',');
        }
      }
    },
    async changeMutipleData(formData, url, model, saveField, showField) {
      try {
        let resp = await this.$axios({
          method: 'get',
          url: url,
        });
        if (resp.data.data) {
          let arr = formData[model].split(',');
          let arr1 = [];
          arr.forEach(it => {
            let temp = resp.data.data.find(o => {
              return o[saveField] == it
            });
            if (temp) {
              arr1.push(temp[showField])
            }
          })
          if (arr1.length > 0) {
            formData[model + '_showValue'] = arr1.join(',');
          }
        }
      }
      catch (error) {}
    },
    async preloadData106() {
      if (this.keyValue) return;
      this.preloadLoading106 = true;
      // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
      try {
        let resp = await this.$axios({
          method: 'get',
          url: baseUrl + '/sales_order?order_number='+this.order_number,
        });
        if (resp.data) {
			let resp2 = await this.$axios({
			  method: 'get',
			  url: baseUrl + '/sales_order/'+resp.data.data.Rows[0].id,
			});
          let {data} = resp.data;
		  for (var i = 0; i < resp2.data.data.businessOpportunityLog.length; i++) {
			  if(!data.Rows[i]){
				  data.Rows[i]={}
				  data.Rows[i].create_date=data.Rows[i-1].create_date;
				  data.Rows[i].contract_number=data.Rows[i-1].contract_number;
				  data.Rows[i].contract_start_date=data.Rows[i-1].contract_start_date;
				  data.Rows[i].contract_end_date=data.Rows[i-1].contract_end_date;
			  }
		  	data.Rows[i].assembly_id=resp2.data.data.businessOpportunityLog[i].assembly_id;
		  }
		  let dynamic =this.getDicData(data.Rows, '{"assembly_name":"assembly_id","order_data":"create_date","contract_number":"contract_number","contract_start_date":"contract_start_date","contract_end_date":"contract_start_date"}');
          this.table115824398679405060000.table115824398679405060000 = dynamic;
          this.preloadLoading106 = false;
        }
      }
      catch (error) {}
      
    },
    getDicData(arr, prestrainFieldsConf) {
      let resultArr = [];
      prestrainFieldsConf = JSON.parse(prestrainFieldsConf) || {};
      arr.map(item => {
        let _obj = {};
        for (let key in prestrainFieldsConf) {
          _obj[key] = item[prestrainFieldsConf[key]];
        }
        resultArr.push(_obj);
      });
      return resultArr;
    },
    // async getField115Options() {
    //   // 注意：this.$axios是通过Vue.prototype.$axios = axios挂载产生的
    //   try {
    //     let resp = await this.$axios({
    //       method: 'get',
    //       url:  baseUrl + '/data-items/SHJG/detail',
    //     });
    //     if (resp.data.data) {
    //       this.descriptionOptions = resp.data.data;
    //     }
    //   }
    //   catch (error) {}
    // },
    async triggerEventHandler(eventData) {
      if (eventData.length > 0) {
        eventData.forEach(ele => {
          let functionName = 'getField' + ele.componentFormId + 'Options';
          if (typeof this[functionName] == "function") {
            this[functionName]();
          }
        })
      }
    },
    triggerEventFormIdHandler(formId) {
      if (this.formFieldsMap.get(formId).__config__.triggerEvents && this.formFieldsMap.get(formId).__config__
        .triggerEvents.length > 0) {
        this.formFieldsMap.get(formId).__config__.triggerEvents.forEach(triggerEventItem => {
          if (this.formFieldsMap.get(formId).__config__.triggerEventData && this.formFieldsMap.get(formId)
            .__config__.triggerEventData[triggerEventItem] && this.formFieldsMap.get(formId).__config__
            .triggerEventData[triggerEventItem].length > 0) {
            this.triggerEventHandler(this.formFieldsMap.get(formId).__config__.triggerEventData[
              triggerEventItem]);
          }
        });
      }
      return true;
    },
    //清空联想弹层、多选弹层的值
    clearBombLayerFormData(filed) {
      this.formData[filed] = '';
      this.formData[filed + '_showValue'] = '';
    },
    // 流程参数赋值
    processParameterAssignment() {
      // 流程中的流程参数赋值 优先级最高，最后赋值
      setTimeout(() => {
        if (this.isEdit != 2 && this.parameter && this.parameter[this.mainTableName]) {
          this.showForm = false;
          for (let [key, value] of Object.entries(this.parameter[this.mainTableName])) {
            this.setFormDataValue(key, value);
          }
          this.showForm = true;
        }
      }, 0);
    },
    setFormDataValue(field, val) {
      if (Array.isArray(this.formData[field])) {
        if (val.includes(',')) {
          this.formData[field] = val.split(',');
        }
        else {
          this.formData[field] = [val];
        }
      }
      else {
        this.formData[field] = val;
      }
      //处理联想弹层，多选弹层
      if (this.formData[field + '_showValue'] != undefined) {
        this.formData[field + '_showValue'] = val;
      }
    },
    setOutputsValue(nodeType, formId, res, outputKey) {
      let nodeTypeChecked = false;
      if (nodeType == 'created') {
        nodeTypeChecked = this.operationVal == 'add';
      }
      else if (nodeType == 'edit') {
        nodeTypeChecked = this.operationVal == 'edit';
      }
      else if (nodeType == 'mounted') {
        nodeTypeChecked = this.operationVal == 'add' || this.operationVal == 'edit';
      }
      if (nodeTypeChecked && this.disabled != true && res && res.data && res.data.data && this.formFieldsMap
        .has(formId) && this.formFieldsMap.get(formId).__vModel__ && this.formData.hasOwnProperty(this
          .formFieldsMap.get(formId).__vModel__)) {
        this.setFormDataValue(this.formFieldsMap.get(formId).__vModel__, res.data.data[outputKey]);
        // 联想弹层 多选弹层 特殊处理
        if (this.formFieldsMap.get(formId).__config__ && this.formFieldsMap.get(formId).__config__.avueType &&
          this.needShowValueTags.includes(this.formFieldsMap.get(formId).__config__.avueType)) {
          this.formData[this.formFieldsMap.get(formId).__vModel__ + '_showValue'] = res.data.data[outputKey];
        }
        this.triggerEventFormIdHandler(formId);
      }
    },
    //子表单权限
    getAuthorityTableChildrenList(bindTable, children) {
      let column = [];
      if (bindTable && this.formEnCodeList && this.formEnCodeList[bindTable]) {
        let formSubEnCodeList = this.formEnCodeList[bindTable];
        if (children && children.length > 0) {
          column = children.map(ele2 => {
            if (formSubEnCodeList.includes(ele2.prop)) {
              ele2.hide = false;
            }
            else {
              ele2.hide = true;
            }
            if (ele2.hide == false) {
              //工作流中系统表单必填权限
              if (this.formSubTableNotRequiredList && this.formSubTableNotRequiredList[bindTable] !=
                undefined) {
                if (this.formSubTableNotRequiredList[bindTable].includes(ele2.prop)) {
                  ele2.required = false;
                }
                else {
                  ele2.required = true;
                }
              }
              ele2.rules = [];
              if (ele2.required) {
                ele2.rules = ele2.ruleList;
              }
              // disabled 属性
              if (this.formSubTableDisabledList && this.formSubTableDisabledList[bindTable] !=
                undefined) {
                if (this.formSubTableDisabledList[bindTable].includes(ele2.prop)) {
                  ele2.disabled = true;
                }
                else {
                  ele2.disabled = false;
                }
              }
              if (this.disabled) { //查看
                ele2.disabled = true;
              }
            }
            else {
              ele2.rules = []
              if (ele2.required) {
                ele2.ruleList.forEach(el => {
                  el.message += ',' + this.$t('noFormAuth')
                })
                ele2.rules = ele2.ruleList;
              }
            }
            return ele2;
          });
        }
        return column;
      }
      else {
        return children;
      }
    },
    async insertCreatedEvent() {
      
    },
    async insertMountedEvent() {
      
    },
    async insertEditEvent() {
      
    },
    async insertSubmitEvent() {
      
    },
    getFormConfig() {
       return fieldsConfig();
    },
    getFormFieldsMap() {
       return formFieldsMap();
    },
    async getHideComponentsMap() {
      let mapList = new Map();
      let hideComponentList = this.getHideComponents();
      if (typeof this.initHideComponentList == 'function') {
        mapList = await this.initHideComponentList(hideComponentList);
        this.$store.commit("SET_HIDE_COMPONENT_LIST", mapList);
      }
      return mapList;
    },
    getHideComponentsMapItem(key) {
      if (this.hideComponentsMap.size > 0) {
        return this.hideComponentsMap.has(key) ? this.hideComponentsMap.get(key) : "";
      }
      else {
        return ""
      }
    },
    getHideComponents() {
       return getHideComponents();
    },
  }
}

</script>
<style>
.el-table__empty-block {
  width: 100% !important;
}

.avue-form__row {
  padding: 0 !important;
}

#editorphone {
  width: 375px;
  margin: 0 auto;
  border: 1px solid #E4E7ED;
  padding: 0 7.5px;
  background: #f5f6fa;
  height: 700px;
  overflow-y: auto;
  overflow-x: hidden;
  border-radius: 5px;
}

#editorphone .el-col {
  border-bottom: 1px solid #F2F2F2;
  background: #fff;
  margin-bottom: 0;
  padding: 0 15px 6px !important;
  width: 100%;
}

#editorphone .el-form-item__label {
  line-height: 20px
}

#editorphone .el-input-group .el-input__inner {
  background: #f5f6fa
}

#editorphone .el-input__inner {
  border: 0
}

#editorphone .el-input-group__append,
#editorphone .el-input-group__prepend {
  border: 0;
  background: #edeef2;
  color: #666;
}

#editorphone .el-input-group .el-input__prefix {
  left: 44px
}

#editorphone .el-input-group .el-input__suffix {
  right: 44px
}

#editorphone .el-form-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  flex-flow: wrap;
}

#editorphone .el-form-item__label {
  float: none;
  min-width: 85px;
  width: auto !important;
  text-align: left;
  flex: auto;
}

#editorphone .tinymce .el-form-item__label {
  min-width: 100%;
}

#editorphone .el-form-item__content {
  margin-left: 0px !important;
  flex: auto;
  width: calc(100% - 95px);
}

#editorphone .avueFormNoLable .el-form-item__label,
#editorphone .avueFormNoLable .avue-crud__pagination {
  display: none;
}

#editorphone .avueFormNoLable .el-collapse-item__wrap,
#editorphone .avueFormNoLable .el-collapse {
  border-bottom: 0
}

#editorphone .avueFormNoLable .el-col {
  border-bottom: 0;
  padding-bottom: 0
}

#editorphone .el-form-item__content .el-button:first-child {
  margin-left: 90px;
}

</style>
